package com.tjshop.android;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tjshop.android.adapter.FragmentTabAdapter;
import com.tjshop.android.constants.UrlConfigs;
import com.tjshop.android.db.userAccess;
import com.tjshop.android.fragment.FragmentCart;
import com.tjshop.android.fragment.FragmentHome;
import com.tjshop.android.fragment.FragmentMine;
import com.tjshop.android.fragment.FragmentCatagory;
import com.tjshop.android.mcv.GlobeVars;
import com.tjshop.android.model.userInfo;
import com.tjshop.android.util.SharedPreferencesUtil;
import com.umeng.message.PushAgent;
import com.umeng.update.UmengUpdateAgent;

/**
 * FIXME 使用注意(trick)： <li>
 * 在onPause(userVisibleHint=true)与onResume(userVisibleHint=true)时进行相应处理</li> <li>
 * 注意不要在Fragment的构造方法执行初始化操作，因为在切换tab的时候其构造方法会执行多次</li> <li>
 * ViewPager滑动时只会将Tab的select状态改为true，但并不会立刻更改focus状态</li>
 * 
 * @author alex hou
 * @since 2014-09-04
 * 
 */
public class MainActivity extends FragmentActivity implements
		View.OnClickListener, Handler.Callback {

	/**
	 * 真正的TabHost用于显示内容的容器id
	 */
	private static final int REAL_TABHOST_ID = R.id.realtabcontent;
	private static final Class<?> TAB_CLASSES[] = { FragmentHome.class,
			FragmentCatagory.class, FragmentCart.class, FragmentMine.class };
	public List<Fragment> fragments = new ArrayList<Fragment>();
	private TabHost mTabHost;
	// private CustomViewPager mViewPager;
	public static Handler mHandler;
	private ImageView splash;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mHandler = new Handler(this);
		setContentView(R.layout.activity_main);
		
		String autoLogin = SharedPreferencesUtil.get(getApplicationContext(), "userinfo", "bautologin");
		if(autoLogin != null && autoLogin.equals("true")){
			autoLogin();
		}
		splash = (ImageView) findViewById(R.id.splash);

		fragments.add(new FragmentHome());
		fragments.add(new FragmentCatagory());
		fragments.add(new FragmentCart());
		fragments.add(new FragmentMine());

		// getSupportActionBar().setCustomView(R.layout.action_bar_title_custom);
		// getSupportActionBar().setDisplayShowCustomEnabled(true);
		// TextView cityText =
		// (TextView)getSupportActionBar().getCustomView().findViewById(R.id.common_title_bar_text);
		// cityText.setOnClickListener(this);

		initTabAndPager();
		GlobeVars.mTabHost = mTabHost;
		userInfo info = new userAccess(this).getUserInfo();
		if (info != null) {
			GlobeVars.UserInfos = info;
			GlobeVars.isLogin = true;
		}
		// umeng started
		// PushAgent mPushAgent =
		// PushAgent.getInstance(getApplicationContext());
		// mPushAgent.enable();
		// UmengUpdateAgent.update(this);

	}

	private void autoLogin() {
		final String username = SharedPreferencesUtil.get(getApplicationContext(), "userinfo", "username");
		final String pass = SharedPreferencesUtil.get(getApplicationContext(), "userinfo", "pass");
		
		if(username!= null && pass != null){
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
					StringRequest stringRequest = new StringRequest(Method.GET,
							UrlConfigs.URL_LOGIN + "?n=" + username + "&p=" + pass,
							new Response.Listener<String>() {
								@Override
								public void onResponse(String response) {
									JSONObject jsonU;
									try {
										jsonU = new JSONObject(response);
										if (jsonU.getInt("r") == 0) {
											GlobeVars.isLogin = true;
											GlobeVars.userId = username;
											GlobeVars.pass = pass;
											GlobeVars.token = jsonU.getString("t");
										} else {
										}
									} catch (JSONException e) {
										e.printStackTrace();
									}
								}
							}, new Response.ErrorListener() {

								@Override
								public void onErrorResponse(VolleyError error) {
								}

							});

					mQueue.add(stringRequest);
				}
			}).start();
		}
	}

	private final static int SCANNIN_GREQUEST_CODE = 1;
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
		case SCANNIN_GREQUEST_CODE:
			if(resultCode == RESULT_OK){
				Bundle bundle = data.getExtras();
				Toast.makeText(getApplicationContext(), bundle.getString("result"), Toast.LENGTH_LONG).show();
			}
			break;
		}
    }	
	@Override
	protected void onResume() {

		super.onResume();
	}

	private void initTabAndPager() {
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();

		FragmentTabAdapter tabAdapter = new FragmentTabAdapter(this, mTabHost,
				fragments, R.id.realtabcontent);

		// 添加相应tab
		for (int i = 0; i < TAB_CLASSES.length; i++) {
			TabSpec tabSpec = mTabHost.newTabSpec("menus").setIndicator(
					createTabView(i));
			tabSpec.setContent(new FragmentTabAdapter.DummyTabFactory(this));

			mTabHost.addTab(tabSpec);
			tabAdapter.notifyDataSetChanged();
		}

	}

	/**
	 * 创建自定义的TabView。
	 * 
	 * @param position
	 *            根据位置动态设置文字/图标
	 * @return
	 */
	private View createTabView(int position) {
		View v = LayoutInflater.from(this).inflate(
				R.layout.inc_common_tab_item, null);

		// 设置文字
		final TextView text = (TextView) v
				.findViewById(R.id.general_tab_item_text);
		text.setText(getResources().getStringArray(
				R.array.general_tab_item_texts)[position]);

		// 设置图标
		ImageView icon = (ImageView) v.findViewById(R.id.general_tab_item_icon);
		TypedArray images = getResources().obtainTypedArray(
				R.array.general_tab_item_icons);
		Drawable drawable = images.getDrawable(position);
		icon.setImageDrawable(drawable);
		images.recycle();

		return v;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// case R.id.common_title_bar_text: // 首页titlebar的城市
		// Intent intent = new Intent(this, CityActivity.class);
		// startActivity(intent);
		// break;
		case R.id.common_title_bar_right_icon:
			Toast.makeText(getApplicationContext(), "暂未开通，敬请期待!",
					Toast.LENGTH_SHORT).show();
			break;
		case R.id.fragment_home_title_bar_search:
			// Bundle b = new Bundle();
			// if(FragmentHome.homeData !=null){
			// String[] kw = new
			// String[FragmentHome.homeData.getKeywords().size()];
			// for(int i = 0;i<FragmentHome.homeData.getKeywords().size();i++){
			// kw[i] = FragmentHome.homeData.getKeywords().get(i);
			// }
			// b.putStringArray("keyword", kw);
			// }else{
			// b.putStringArray("keyword", new String[0]);
			// }
			// Intent intent = new Intent(getApplicationContext(),
			// SearchActivity.class);
			// intent.putExtras(b);
			// startActivity(intent);
			break;

		}
	}

	@Override
	public boolean handleMessage(Message arg0) {
		splash.setVisibility(View.GONE);
		return false;
	}
}
